<template>
    <el-alert
        v-if="type !== '0' && !!form.id"
        :title="['审核中', '审核通过', '审核拒绝'][form.auditStatus]"
        :type="['warning', 'success', 'error'][form.auditStatus]"
        :description="
            form.auditStatus
                ? `${form.auditRemarks ? form.auditRemarks : ''} ${form.auditTime ? form.auditTime : ''}`
                : ''
        "
        show-icon
        :closable="false"
    />
    <el-form ref="formRef" :model="form" label-position="top" inline :rules="rules">
        <div class="item">
            <div class="title">客户信息</div>
            <el-row>
                <el-col v-if="isCrm" :span="24">
                    <el-form-item label="投放主体">
                        <SelectRemote
                            ref="selectRemote"
                            class="select-remote"
                            :disabled="type !== '0'"
                            :target-data="form.customerDTO.deliverySubject"
                            :basic-info="{ value: 'industryCode', label: 'deliverySubject', key: 'industryCode' }"
                            @onChange="(val: any) => onCrmChange(val)"
                        >
                            <template #icon>
                                <el-icon><Search /></el-icon>
                            </template>
                        </SelectRemote>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="客户类型" prop="customerDTO.type">
                        <el-select
                            v-model="form.customerDTO.type"
                            placeholder="请选择"
                            :disabled="type !== '0' || isCrm"
                        >
                            <el-option label="企业" :value="1"></el-option>
                            <el-option label="个人" :value="2"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col v-if="form.customerDTO.type !== ''" :span="12">
                    <el-form-item label="品牌名称" prop="customerDTO.brand">
                        <el-input
                            v-model="form.customerDTO.brand"
                            placeholder="搜索客户"
                            :disabled="type !== '0' || isCrm"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row v-if="form.customerDTO.type === 1 && !isCrm">
                <el-col :span="24">
                    <el-form-item label="投放主体" prop="customerDTO.deliverySubject">
                        <el-input
                            v-model="form.customerDTO.deliverySubject"
                            placeholder="请输入"
                            :disabled="type !== '0' || isCrm"
                            class="ipt-icon"
                        >
                            <template #prefix>
                                <el-icon><Search /></el-icon>
                            </template>
                        </el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row v-if="form.customerDTO.type === 1">
                <el-col :span="24">
                    <el-form-item label="签约主体" prop="customerDTO.signName">
                        <el-input
                            v-model="form.customerDTO.signName"
                            placeholder="请输入"
                            :disabled="type !== '0' || isCrm"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col v-if="form.customerDTO.type === 2" :span="12">
                    <el-form-item label="签约人姓名">
                        <el-input
                            v-model="form.customerDTO.signName"
                            placeholder="搜索客户"
                            :disabled="type !== '0' || isCrm"
                        />
                    </el-form-item>
                </el-col>
                <el-col v-if="form.customerDTO.type !== ''" :span="12">
                    <el-form-item label="客户行业" prop="customerDTO.industryCode">
                        <el-select
                            v-model="form.customerDTO.industryCode"
                            placeholder="请选择"
                            :disabled="type !== '0' || isCrm"
                        >
                            <el-option
                                v-for="item in industryList1"
                                :key="item.code"
                                :label="item.name"
                                :value="item.code"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
        </div>
        <div class="item mt16">
            <div class="title">制作创意</div>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="创意名称" prop="name">
                        <el-input v-model="form.name" placeholder="请输入" :disabled="type === '1'" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="创意行业" prop="industryCode">
                        <el-select v-model="form.industryCode" placeholder="请选择" :disabled="type === '1'" filterable>
                            <el-option
                                v-for="item in industryList2"
                                :key="item.code"
                                :label="item.name"
                                :value="item.code"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="媒体类型" label-width="260px">
                        <el-select v-model="form.mediaType" :disabled="true" placeholder="请选择">
                            <el-option label="梯内屏" :value="1"></el-option>
                            <el-option label="梯外屏" :value="2"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="创意时长" prop="time">
                        <el-select v-model="form.time" placeholder="请选择" :disabled="type === '1'">
                            <el-option v-for="time in timeList" :key="time" :label="`${time}s`" :value="time" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="屏幕类型">
                        <el-select v-model="form.screenType" placeholder="请选择" :disabled="type === '1'">
                            <el-option label="联动" :value="1"></el-option>
                            <el-option label="上屏" :value="2"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
        </div>
    </el-form>
    <div class="item mt16">
        <div class="title">素材规格</div>
        <div class="flex-box">
            <div v-if="form.mediaType === 1" class="screen">
                <XcScreenType
                    screen-type="inner"
                    :top="screenTopInfo"
                    :bottom="{ resourcesType: 1, src: brInfo.url }"
                />
            </div>

            <!-- 梯外时 展示三屏和单屏 -->
            <div v-if="form.mediaType === 2" class="screen flex-box">
                <div class="out-screen">
                    <XcScreenType
                        screen-type="out"
                        :top="{ ...screenTopInfo }"
                        :bottom="{ resourcesType: 1, leftSrc: blInfo.url, rightSrc: brInfo.url }"
                        @on-play="onScreenPlay"
                        @get-instance="getOutScreenInstance"
                    />
                </div>
                <div class="single-screen">
                    <XcScreenType
                        screen-type="single"
                        :top="{ ...outSingScreenTopInfo }"
                        :autoplay="false"
                        @on-play="onScreenPlay"
                    />
                </div>
            </div>
        </div>
        <div class="item mt16">
            <div class="title">期望创意有效期</div>
            <div class="t">创意有效期</div>
            <el-date-picker
                v-model="form.expectEffectiveTime"
                :disabled="form.id && form.auditStatus !== 2"
                type="date"
                placeholder="请选择期望创意有效期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                :disabled-date="pickerOptions.disabledDate"
            />
        </div>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, defineExpose, defineProps, watchEffect, computed } from 'vue';
// import XcScreenType from '@x-tech/fe-pc-components/src/components/XcScreenType/index.vue';
import XcScreenType from './XcScreenType.vue';
import SelectRemote from './SelectRemote.vue';
import { Search } from '@element-plus/icons-vue';
import { useStore } from 'vuex';
import pic_hint from '@/assets/pic_hint@2x.png';
import type { FormInstance, FormRules } from 'element-plus';

import { getQualificationConf } from '@/api/delivery/creativeManage';
import { getIndustryFirstList, getIndustrySecondList } from '@/api/delivery/customerManage';

const store = useStore();
const isCrm = computed(() => store.state.userGroup.userInfo?.useCrm);
const formRef = ref<FormInstance>();

let form = reactive<any>({
    expectEffectiveTime: '',
    mediaType: 1,
    screenType: 1,
    customerDTO: {},
    materialDtoList: [],
    adQualificationDtoList: [],
});
let pickerOptions = reactive<any>({
    disabledDate: (time: { getTime: () => number }) => {
        // 设置可选择的日期为今天之后的365天内
        const curDate = new Date().getTime();
        // 这里算出365天的毫秒数,这里使用30的平均值, 实际中应根据具体的每个月有多少天计算;
        const day = 365 * 24 * 3600 * 1000;
        const dateRegion = curDate + day;
        return time.getTime() < Date.now() - 8.64e7 || time.getTime() > dateRegion;
    },
});

const props = defineProps({
    type: {
        type: String,
        default: '',
    },
    detail: {
        type: Object,
        default: () => {},
    },
});

const timeList = ref<number[]>([]);
const typeInfo = ref<any>('');
const getTimeList = () => {
    let times = [];
    for (let i = 1; i <= 36; i++) {
        times.push(i * 5);
    }
    return times;
};

timeList.value = getTimeList();

const isPdf = (filePath: string): boolean => {
    return /^.+(\.pdf)$/.test(filePath);
};

const credentials = ref('');
const industryList1 = ref<any>([]);
const industryList2 = ref<any>([]);

const topInfo = reactive({
    name: '',
    url: '',
    showUrl: '',
});
const blInfo = reactive({
    name: '',
    url: '',
});
const brInfo = reactive({
    name: '',
    url: '',
});
const outSingInfo = reactive({
    name: '',
    url: '',
    showUrl: '',
});
const adList = ref<any>([]);

const rules = reactive<FormRules>({
    'customerDTO.brand': [{ required: true, message: '请输入品牌名称', trigger: 'blur' }],
    'customerDTO.type': [{ required: true, message: '请选择客户类型', trigger: 'change' }],
    'customerDTO.industryCode': [{ required: true, message: '请选择客户行业', trigger: 'change' }],
    'customerDTO.deliverySubject': [{ required: !isCrm.value, message: '请输入投放主体', trigger: 'change' }],
    'customerDTO.signName': [{ required: !isCrm.value, message: '请输入签约主体', trigger: 'change' }],
    name: [{ required: true, message: '请输入创意名称', trigger: 'blur' }],
    industryCode: [{ required: true, message: '请选择创意行业', trigger: 'change' }],
    time: [{ required: true, message: '请选择创意时长', trigger: 'change' }],
});

// 梯内和梯外的 上屏信息
const screenTopInfo = computed(() => {
    // 如果存在转码后的视频 直接展示视频格式
    if (topInfo.showUrl) {
        return {
            resourcesType: 2,
            src: topInfo.showUrl,
        };
        // 新建和没转码成功 直接展示正在转码中的图片
    } else if (!topInfo.showUrl && !!topInfo.url) {
        return {
            resourcesType: 1,
            src: pic_hint,
        };
    }
    return {
        resourcesType: 1,
        src: '',
    };
});

// 梯外单屏预览信息
const outSingScreenTopInfo = computed(() => {
    // 如果存在转码后的视频 直接展示视频格式
    if (outSingInfo.showUrl) {
        return {
            resourcesType: 2,
            src: outSingInfo.showUrl,
        };
        // 新建和没转码成功 直接展示正在转码中的图片
    } else if (!outSingInfo.showUrl && !!outSingInfo.url) {
        return {
            resourcesType: 1,
            src: pic_hint,
        };
    }
    return {
        resourcesType: 1,
        src: '',
    };
});

const remarkMargin = computed(() => !!form.auditRemarks || !!form.auditTime ? '5px 0' : '');

watchEffect(() => {
    if (form.materialDtoList.length) {
        topInfo.url = form.materialDtoList.find((item: any) => item.position === (form.mediaType === 1 ? 1 : 4))?.url;
        topInfo.showUrl = form.materialDtoList.find(
            (item: any) => item.position === (form.mediaType === 1 ? 1 : 4)
        )?.showUrl;

        outSingInfo.url = form.materialDtoList.find((item: any) => item.position === 7)?.url;
        outSingInfo.showUrl = form.materialDtoList.find((item: any) => item.position === 7)?.showUrl;

        blInfo.url = form.materialDtoList.find((item: any) => item.position === (form.mediaType === 1 ? 3 : 5))?.url;
        brInfo.url = form.materialDtoList.find((item: any) => item.position === (form.mediaType === 1 ? 2 : 6))?.url;

        topInfo.name = topInfo.name ? topInfo.name : topInfo.url?.substring(topInfo.url.lastIndexOf('/') + 1);
        outSingInfo.name = outSingInfo.name
            ? outSingInfo.name
            : outSingInfo.url?.substring(outSingInfo.url.lastIndexOf('/') + 1);

        blInfo.name = blInfo.name ? blInfo.name : blInfo.url?.substring(blInfo.url.lastIndexOf('/') + 1);
        brInfo.name = brInfo.name ? brInfo.name : brInfo.url?.substring(brInfo.url.lastIndexOf('/') + 1);
    } else {
        topInfo.url = '';
        outSingInfo.url = '';
        blInfo.url = '';
        brInfo.url = '';
    }
});

const onCrmChange = (customerDTO: any) => {
    form.customerDTO.deliverySubject = customerDTO.deliverySubject;
    form.customerDTO.industryCode = customerDTO.industryCode;
    form.customerDTO.brand = customerDTO.brand;
    form.customerDTO.type = customerDTO.type;
    form.customerDTO.customerId = customerDTO.customerId;
    form.customerDTO.signName = customerDTO.signName;
};

// 控制屏幕播放逻辑
let curPlayingScreen: any = null;
const onScreenPlay = (screenTypeIns: any) => {
    if (curPlayingScreen) {
        curPlayingScreen.setPauseState();
    }
    curPlayingScreen = screenTypeIns;
};
const getOutScreenInstance = (screenTypeIns: any) => {
    curPlayingScreen = screenTypeIns;
};
onMounted(async () => {
    if (props.detail) {
        form.expectEffectiveTime = '';
        form = Object.assign(form, props.detail);
        // form.mediaType = 2; // 测试
    }
    try {
        const data: any = await Promise.allSettled([
            getIndustryFirstList(),
            getIndustrySecondList(),
            getQualificationConf(),
        ]);
        if (data[0].status === 'fulfilled') {
            industryList1.value = data[0]?.value;
        }
        if (data[1].status === 'fulfilled') {
            industryList2.value = data[1]?.value;
        }
        if (data[2].status === 'fulfilled') {
            adList.value = data[2]?.value;
        }
    } catch (error) {
        console.log(error);
    }
});

defineExpose({
    form,
    formRef,
});
</script>

<style lang="scss" scoped>
.flex-box {
    display: flex;
}

.flex {
    flex: 1;
}

.item {
    width: 100%;

    .title {
        font-size: 16px;
        font-weight: 700;
        color: #333;
        margin-bottom: 16px;
    }

    .t {
        font-size: 14px;
        font-weight: 400;
        color: #333;
        margin-bottom: 16px;
    }

    .screen {
        margin-right: 16px;
        .out-screen {
            // transform: scale(0.8, 0.8);
            margin-right: 20px;
        }
        .single-screen {
            // transform: scale(0.8, 0.8);
        }
    }
}

.mt30 {
    margin-top: 30px;
}

.mt16 {
    margin-top: 16px;
}

.imgUpload {
    height: 66px;
    padding: 0 15px;
    background: #ffffff;
    border-radius: 4px 4px 4px 4px;
    opacity: 1;
    border: 1px solid #d9d9d9;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 10px 15px 16px 0;

    .imgInfo {
        display: flex;
        align-items: center;

        .img-name {
            font-size: 14px;
            padding: 0 10px;
            word-break: break-all;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            overflow: hidden;
        }
    }

    .el-icon {
        cursor: pointer;
    }
}

.el-alert {
    padding: 20px;
    align-items: center;
    margin-bottom: 16px;

    ::v-deep(.el-alert__title) {
        font-size: 16px;
        font-weight: 500;
        color: #252525;
    }

    ::v-deep(.el-alert__description) {
        font-size: 14px;
        font-weight: 400;
        color: #bcbcbc;
        margin: v-bind(remarkMargin);
    }
}

::v-deep(.el-upload-list) {
    width: 260px;
}

::v-deep(.select-remote.select .el-input__inner) {
    padding-left: 31px;
}

::v-deep(.ipt-icon .el-input__prefix-inner) {
    display: flex;
    align-items: center;
}
</style>
